# -*- coding:utf-8 -*-

import xlrd
import xlwt
from config import config
from xlutils.copy import copy
import sys


import os


def new_excel(file=config.OUT_FILE):
    print(u'发现写入目标不存在，正在创建文件', file)
    book = xlwt.Workbook(encoding='utf-8', style_compression=0)
    book.add_sheet('sheet1', cell_overwrite_ok=True)
    book.save(file)
    print(u'已成功创建文件', file)


def repeat_excel(match, pick, file=config.OUT_FILE):
    # print(u'正在检测', match, pick, u'是否存在于文件中'
    try:
        workbook = xlrd.open_workbook(file)
        sheet = workbook.sheet_by_index(0)
        words = sheet.col_values(0)
        picks = sheet.col_values(1)

        if (match in words) and (pick in picks):
            # print(u'已经存在', match, ' ||  ', pick, u'跳过!'
            return True
        else:
            return False
    except IOError:
        new_excel(file)
        return False


def write_to_excel(rowlist, file=config.OUT_FILE):
    print(u'正在写入到文本中')
    try:
        rb = xlrd.open_workbook(file)
        sheet = rb.sheets()[0]
        row = sheet.nrows
        wb = copy(rb)
        sheet = wb.get_sheet(0)

        for rowdata in rowlist:
            count = 0
            match = rowdata[0]
            pick = rowdata[1]
            if not repeat_excel(match, pick, file):
                for rowdataitem in rowdata:
                    sheet.write(row, count, rowdataitem)
                    count = count + 1

                print(u'成功写入  ', match, ' ||  ', pick, u'!')
                # print(u'已成功内存写入到文件', file, u'第', row + 1, u'行'
            row = row + 1
        wb.save(file)
    except IOError:
        print(u'未找到该文件', file)
        book = xlwt.Workbook(encoding='utf-8', style_compression=0)
        book.add_sheet('sheet1', cell_overwrite_ok=True)
        book.save(file)
        print(u'已成功创建该文件', file)
        write_to_excel(rowlist, file)


def write_info(blogname, rowlist):
    xls_file = config.get_excel_name_s(blogname, 'a')
    write_to_excel(rowlist, xls_file)


def delete_file(file):
    try:
        os.remove(file)
    except OSError:
        print('new xls! to be create!')


def get_file(name):
    try:
        with open(config.get_file_name(name), 'r') as f:
            page = f.read()
            if not page:
                return ''
            else:
                return page
    except Exception:
        print('get_file err')
        return ''


def write_count(count, file):
    try:
        with open(file, 'w+') as f:
            f.write(str(count))
            f.close()
    except TypeError:
        print(u'页码写入失败')


def writeTxt(txtlines, file):
    try:
        with open(file, 'a') as f:
            f.writelines(txtlines)
            f.close()
    except TypeError:
        print(u'页码写入失败')
